#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
    vector<int> B, A, AB;
//    priority_queue<int> B, A, AB;
    int n, k; cin >> n >> k;
    for (int i = 0; i < n; ++i) {
        int t, a , b; cin >> t >> a >> b;
        if(a && b) AB.push_back(t);
        else if(a && !b) A.push_back(t);
        else if(!a && b) B.push_back(t);
    }
    sort(A.begin(), A.end()), sort(B.begin(), B.end()), sort(AB.begin(), AB.end());
    if(AB.size() + min(A.size(), B.size()) >=k){
        int i , l, r; i = l = r = 0;
        int ans = 0, cnt = 0;
        while (cnt < k){
            if(i<AB.size() && l < A.size() && r < B.size()){
                if(AB[i] < A[l]+B[r]) ans += AB[i++];
                else ans += A[l++] + B[r++];
            }else if(i==AB.size() && l < A.size() && r < B.size()) ans += A[l++] + B[r++];
            else if(i<AB.size() && !(l < A.size() && r < B.size())) ans += AB[i++];
            ++cnt;
        }
        cout << ans << "\n";
    }else cout << -1 << "\n";
    return 0;
}